/**
 * Created by Administrator on 2017/10/22.
 */
/**
 扩展一个layui模块,用户自动绑定页面增加、删、改按钮事件
 **/

layui.define('layer',function(exports){ //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
    var layer = layui.layer;
    function BtnEventHandler(){};

    BtnEventHandler.prototype.bound = function($table, addBtnId,editBtnId, delBtnId){
        if(addBtnId){
            var $addBtn = $("#" + addBtnId);
            $addBtn.on('click',function(){
                var url = $(this).data("url");
                location.href = url;
            });
        }

        if(editBtnId) {
            var $editBtn = $("#" + editBtnId);
            $editBtn.on('click',function(){
                var rows = $table.bootstrapTable('getSelections');  //获取选中行
                if(rows.length < 1) {
                    layer.msg("请勾选一条数据");
                }else if(rows > 1) {
                    layer.msg("只能勾选一条数据");
                }else {
                    var id = rows[0].id;
                    var url = $(this).data("url");
                    location.href = url + "?id=" + id;
                }
            });
        }


        if(delBtnId) {
            var $delBtn = $("#" + delBtnId);
            $delBtn.on('click',function(){
                var $rows = $table.bootstrapTable('getSelections');  //获取选中行
                if($rows.length < 1) {
                    layer.msg("请勾选一条数据");
                }else {
                    layer.confirm("您确定要删除勾选的所有数据吗？",function(index){
                        //异步删除 所选记录
                        location.href = url;
                        var ids = [];
                        $rows.each(function(){
                            var id = this.id;
                            ids.push(id);
                        });

                        $.ajax({
                            url: url,
                            type:"post",
                            data:{ids:ids.join(",")},
                            dataType:'json',
                            success:function(msg) {
                                if(msg.code == 1) {
                                    layer.msg(msg.message);
                                }else {
                                    console.log(msg.message);
                                    layer.msg("服务器忙，请稍后再试");
                                }
                            },
                            error:function(e){
                                layer.msg("请求失败");
                            }
                        });
                    })
                }
            });
        }
    }
    //输出test接口
    exports('btnEvent', new BtnEventHandler());
});